package com.gcloud.mesh.dcs.chain.ali;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.ecs20140526.models.AllocatePublicIpAddressRequest;
import com.gcloud.mesh.dcs.chain.FilterChain;
import com.gcloud.mesh.dcs.chain.IMigrationStepChain;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.MyBusinessException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

//@Component
@Slf4j
public class AllocatePublicIpAddress_8 extends AbstractAliMigrationStep {

    String ip = null;

    @Override
    public String getExecResult() {
        if(StringUtils.isEmpty(this.ip)) return null;
        return "公网IP为："+this.ip;
    }

    @Override
    public void doExec(String schedulerJobId, String attach, FilterChain filterChain, IMigrationStepChain stepChain) {
        JSONObject jsonObject = JSONObject.parseObject(attach);
        String regionId = jsonObject.getString("regionId");
        String accessKeyId = jsonObject.getString("accessKeyId");
        String accessSecret = jsonObject.getString("accessSecret");
        String dstInstanceId = jsonObject.getString("dstInstanceId");
        this.ip = this.allocatePublicIpAddress(accessKeyId, accessSecret, regionId, dstInstanceId);
        filterChain.doExec(schedulerJobId,attach,filterChain,stepChain);
    }

    @Override
    public String chainName(String attach) {
        return "分配公网IP";
    }

    @Override
    public int getOrder() {
        return 8;
    }

    public String allocatePublicIpAddress(String accessKeyId, String accessKeySecret , String regionId,String InstanceId){
        try {
            com.aliyun.ecs20140526.Client client = createECSClient(accessKeyId,accessKeySecret,regionId);
            AllocatePublicIpAddressRequest allocatePublicIpAddressRequest = new AllocatePublicIpAddressRequest()
                    .setInstanceId(InstanceId);
            return client.allocatePublicIpAddress(allocatePublicIpAddressRequest).getBody().getIpAddress();
        } catch (Exception e) {
            log.error("分配实例公网IP失败",e);
            throw new MyBusinessException("分配实例公网IP失败"+"::"+e.getMessage());
        }
    }
}
